#include "types.h"
#include "backend.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

/* Put a key triplet in the store.
 */
int register_triplet(user_t who,
		     key_t k1, key_t k2, key_t k3,
		     struct timeval *gap1,
		     struct timeval *gap2)
{
	printf("%ld bpm  \n", (60000000) / (gap1->tv_sec*1000000 + gap1->tv_usec));

	return 0;
}

/* Called by the frontend when a key has been struck, this computes
 * the difference and sends it along to register_triplet.
 */
void key_struck(key_t which)
{
	static struct timeval *time1, *time2, *time3;
	static key_t key1, key2, key3;

	/* Init the crap out of the variables.  TODO: check for
	 * failure to allocate.
	 */
	if (time1 == NULL)
		time1 = malloc(sizeof(struct timeval));
	if (time2 == NULL)
		time2 = malloc(sizeof(struct timeval));
	if (time3 == NULL)
		time3 = malloc(sizeof(struct timeval));


	struct timeval *tmp1, *tmp2;
	tmp1 = malloc(sizeof(struct timeval));
	tmp2 = malloc(sizeof(struct timeval));

	key1 = key2;
	key2 = key3;
	key3 = which;

	/* Oh yeah - chomp through a malloc on every keystroke.  This
	 * has to be efficient.  *shrug*
	 */
	if (time1)
		free(time1);
	time1 = time2;
	time2 = time3;
	time3 = malloc(sizeof(struct timeval));

	gettimeofday(time3, NULL);

	timersub(time2, time1, tmp1);
	timersub(time3, time2, tmp2);

	register_triplet(whoisit(),
			 key1, key2, key3,
			 tmp1, tmp2);
}

/* Returns the identity user who seems to be typing.  If we're
 * training, this doesn't have to be guessed.
 */
user_t whoisit(void)
{
	return (user_t) 0;
}
